
package Database;

import java.sql.DriverManager;

/**
 *
 * @author Raed Shomali
 */
public class PoolDatabaseManager 
{
    private static final String HOST = "localhost" ;
    private static final String PORT = "3306" ;
    private static final String DB_NAME = "jugdb" ;
    private static final String USERNAME = "root" ;
    private static final String PASSWORD = "root" ;
    
    public static String DB_DRIVER = "com.mysql.jdbc.Driver" ;
    public static String DB_TYPE = "mysql" ;
    
    // Static Blocks Executes When Server is Up
    static
    {
        registerDriver() ;
    }
    
    public static boolean registerDriver()
    {
        // Keep Track Of Driver Being Registered
        boolean isSuccessful = false ;
        
        try
        {
            String DB_URL = "jdbc:" + DB_TYPE + "://" + HOST + ":" + PORT + "/" + DB_NAME ;
            
            new DBConnectionDriver( DB_DRIVER , DB_URL , USERNAME ,PASSWORD );
            
            // Driver Registered Successfully
            isSuccessful = true ;
        }
        catch ( Exception e )
        {
            // Driver Failed To be Registered
            
            e.printStackTrace();
        }
        
        return isSuccessful ;
    }

    public static DBConnection getConnection()
    {
        try
        {
            System.out.println( "Connecting ..." );
            
            // Connection Object
            DBConnection connection = (DBConnection) DriverManager.getConnection( "jdbc:jdc:jdcpool" );
    
            System.out.println( "Connected to Database !" );
            
            // For Better Performance (Batch Commiting)
            connection.setAutoCommit( false ) ;
            
            return connection;
        }
        catch( Exception e )
        {
            e.printStackTrace() ;
            
            // Sorry, We were unable to Connect to the Database.
            System.out.println( "Unable to connect to Database." );
            
            return null;
        }
    }

    public static void disconnect( DBConnection connection )
    {
        // Make Sure Passed Connection Exists.
        if( connection != null )
        {
            try
            {
                System.out.println( "Committing ..." );
            
                // Save
                connection.commit() ;
   
                System.out.println( "Data Committed !" );
            
                System.out.println( "Disconnecting ..." );
    
                // Free Resources
                connection.close();
                
                System.out.println( "Disconnected from Database !" );
            }
            catch( Exception e )
            {
                System.out.println( "Could Not Disconnect Database: " + e.getMessage() );
            }
        }
    }
}
